package cn.easyutil.deploy;

import cn.easyutil.deploy.base.Command;
import cn.easyutil.deploy.base.Project;
import cn.easyutil.deploy.executor.CommandExecutorBuilder;
import cn.easyutil.deploy.util.SystemIn;
import cn.easyutil.deploy.service.OpenApi;

import java.util.List;
import java.util.stream.Collectors;

public class Main {

    //项目名称
    private static String DP;

    //指令简称
    private static String DC;

    //脚本创建路径
    private static String scriptPath;

    public static void main(String[] args) {

        //解析jvm参数
        parseArgs(args);
        //获取实例
        OpenApi openApi = OpenApi.loadByFile(null);
        //模糊搜索项目
        List<Project> projects = openApi.findProjects(DP);
        //让用户选择项目
        int checkProject = SystemIn.check(projects.stream().map(Project::getProjectName).collect(Collectors.toList()));
        Project project = projects.get(checkProject);
        //模糊搜索指令
        List<Command> commands = openApi.findCommands(project, DC);
        //让用户选择指令
        int checkCommand = SystemIn.check(commands.stream().map(Command::getCommandName).collect(Collectors.toList()));
        Command command = commands.get(checkCommand);
        //执行命令
        openApi.exec(project,command, CommandExecutorBuilder.build(project,s->{
            System.out.println(s);
        }));


    }


    private static void parseArgs(String[] args){
        for (String arg : args) {
            if("--HELP".equals(arg.toUpperCase())){
                SystemIn.help();
            }
            if(arg.toUpperCase().startsWith("-D")){
                if(arg.contains("=")){
                    DP = arg.split("=")[1];
                }else{
                    DP = arg.substring(arg.indexOf("-D")+2);
                }
            }
            if(arg.toUpperCase().startsWith("--")){
                if(arg.contains("=")){
                    DC = arg.split("=")[1];
                }else{
                    DC = arg.substring(arg.indexOf("--")+2);
                }
            }
            if(arg.toUpperCase().startsWith("SCRIPTPATH=")){
                String p = arg.substring(arg.toUpperCase().indexOf("SCRIPTPATH=") + 11);
                try {
                    scriptPath = p;
                }catch (Exception ignored){}
            }
        }
    }
}
